<?php

class HardwareController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->list_sess_unset('controller_hardware');
        $this->session_search_key = 'controller_hardware';
        $this->session_search_name = 'search_label';
        
        
        if ($this->_getParam('hard_id') && $this->_getParam('hard_id') != "") {
            $hard_id = $this->_getParam('hard_id');
            $hardwareModel = new Model_Hardware();
            $hardwaredata = $hardwareModel->fetchEntryByViewId($hard_id);
            if($this->USER->role != 'ADMIN'){
                if($hardwaredata['com_id'] != $this->USER->company_id){
                    $this->_helper->redirector('list', 'hardware', '');
                }
            }
        }
        
        
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'hardware', '');
    }

    public function viewAction() {
        if ($this->_getParam('hard_id') && $this->_getParam('hard_id') != "") {
            $hard_id = $this->_getParam('hard_id');
        } else {
            $this->_helper->redirector('list', 'hardware', '');
        }
        $hardwareModel = new Model_Hardware();
        $hardwaredata = $hardwareModel->fetchEntryByViewId($hard_id);
        $updated_id = $hardwaredata['lgn_id'];
        $login_type = $hardwaredata['lgn_type'];

        /*         * get user name which is updated data* */
        $loginModel = new Model_Login();
        $updated_by_user = $loginModel->getUserData(Array('lgn_id' => $updated_id));
        $user_name = ucfirst($updated_by_user->name) . " [" . ucfirst($updated_by_user->role) . "]";

        $this->view->admindata = $user_name;
        $this->view->hardwaredata = $hardwaredata;
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "1 = 1 ";
        $searchtype = "";
        $orderField = 'hard_id';
        $sort = 'asc';
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }


        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;
        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }
        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }
        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }
        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = $this->ZFTRANSLATE->translate("select_one_checkbox");
                }
            }

            /* Search Facility Over Here */
            if ($postedData["searchtype"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                if ($searchtype != '') {
                    $where = "hard_name LIKE '%$searchtype%' OR build_name LIKE '%$searchtype%' ";
                    $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
                    $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
                }
            }
        } else {
            $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            $where = "hard_name LIKE '%$searchtype%' OR build_name LIKE '%$searchtype%' ";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
            $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
        }

        if ($this->USER->roletype == 'Contractor' || $this->USER->roletype == 'SuperContractor' ||
                $this->USER->roletype == 'Customer' || $this->USER->roletype == 'SuperCustomer') {
            $where .=' ) AND (site.com_id=' . $this->USER->company_id;
        } else {
            $where .='';
        }

        if ($this->_getParam('site_id') && $this->_getParam('site_id') != "") {
            $where .= ")AND (build.site_id = '" . $this->_getParam('site_id') . "'";
        }

        $hardwareModel = new Model_Hardware();
        $hardwaresData = $hardwareModel->fetchHardware($where, $itemsPerPageReviews, $offset, $orderField, $sort);
        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($hardwareModel->getHardwareCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'hardware', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->hardwaresData = $hardwaresData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $hardwareModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load Hardware Model 
        $hardwareModel = new Model_Hardware();
        if ($this->_getParam('hard_id') && $this->_getParam('hard_id') != "") {
            $hardware_id = $this->_getParam('hard_id');
            $hardwareModel->deleteHardware($hardware_id);

            $this->addSuccessMessage($this->ZFTRANSLATE->translate("hard_delete_success"));
            $this->_helper->redirector('list', 'hardware', '');
        } else {
            $hardwareModel->deleteHardware($ids);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("hard_delete_success"));
            $this->_helper->redirector('list', 'hardware', '');
        }
    }

    public function formAction() {

        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $hardwareData = Array();
        $this->view->mode = "Add";


        //Load Hardware Model
        $hardwareModel = new Model_Hardware();

        //Load Hardware Form
        $hardwareForm = new Form_HardwareForm();

        $imageName = "";


        //Load the site array for the select box in form 
        /* $siteArray = $hardwareModel->getsiteArray();
          $hardwareForm->site_id->addMultiOptions($siteArray);
         */

        //Load the building array for the select box in form 
        $buildingArray = $hardwareModel->getbuildingArray();
        $hardwareForm->build_id->addMultiOptions($buildingArray);

        //Load the status array for the select box in form 
        $statusArray = $hardwareModel->getStatusArray();
        $hardwareForm->hard_status->addMultiOptions($statusArray);

        //Check for the hardware Parameter
        $hardwareData['hard_id'] = $this->_request->getParam('hard_id');
        $hard_id = (!empty($hardwareData['hard_id'])) ? $hardwareData['hard_id'] : null;

        if (!empty($hard_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $hardwareModel->fetchEntryById($hard_id);
            $imageName = $data['hard_image'];
            $this->imagename = $imageName;
        }
        //Populate form 
        $this->view->form = $hardwareForm->populate($data);
        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();
            if (!$hardwareForm->isValid($postedData)) {
                $errorMessage = $hardwareForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                if (count($errorMessageArray) > 0) {
                    
                } else {


                    $upload = new Zend_File_Transfer_Adapter_Http();
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                            $folder = $this->config->UPLOAD_PATH . "hardware/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);
                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);
                            $hardwareData['hard_image'] = $fileName;
                        }
                    }


                    if ($this->view->mode == "Add") {
                        $HardwareCount = $hardwareModel->getHardwareCount('');
                        $hardwareData['hard_createddate'] = date("Y-m-d H:i:s");
                    }

                    /*                     * authentication login id */
                    $defaultSession = new Zend_Session_Namespace(Zend_Registry::get('sessionName'));
                    $defaultSessionVal = $defaultSession->getIterator();
                    $updated_userid = $defaultSessionVal['storage']->lgn_id;

                    //Hardware save
                    $hardwareData['updated_lgn_id'] = $updated_userid;
                    $hardwareData['hard_id'] = $hard_id;
                    $hardwareData['build_id'] = $postedData['build_id'];
                    $hardwareData['hard_name'] = $postedData['hard_name'];
                    $hardwareData['hard_serial'] = $postedData['hard_serial'];
                    $hardwareData['hard_exp_date'] = $postedData['hard_exp_date'];
                    $hardwareData['hard_location'] = $postedData['hard_location'];
                    $hardwareData['hard_status'] = $postedData['hard_status'];
                    $hardwareData['hard_updateddate'] = date("Y-m-d H:i:s");

                    $hardwareModel->save($hardwareData, 'hard_id');

                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("hard_add_success");
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("hard_update_success");
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'hardware', '');
                }
            }
        }
        $this->view->mode = $this->view->mode;
        $this->view->hardid = $hard_id;
        $this->view->imageName = $imageName;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $hardwareForm;
    }

}

?>
